﻿using System.Linq;
using BingoClientModel;
using BingoHallServerConsole.Model;
using BingoServerCommon.Common;
using BingoServerCommon.DbModel;
using Dapper;
using MySql.Data.MySqlClient;

namespace BingoHallServerConsole.Business.Mall
{
	/// <summary>
	/// 客户端请求商城里的商品列表
	/// </summary>
	public class CS_MallGetAllCommodities : Package
	{


		public CS_MallGetAllCommodities(EnumPackCommand mainid) : base(mainid)
		{
		}

		public CS_MallGetAllCommodities(byte[] buffer, int len) : base(buffer, len)
		{
		}

		public override Package Clone(byte[] bytes)
		{
			return new CS_MallGetAllCommodities(bytes, bytes.Length);
		}





		/// <summary>
		/// 查商城商品与购买商城商品
		/// type参数是商品类型，是入场券还是道具，还是其他
		/// </summary>
		public override void Excute(Session session)
		{
			var type = ReadInt(); // 对应门票还是入场券的枚举类型，EnumCommodityType

			MySqlConnection conn = Program.ConnectionPool.getConnection(); //从连接池拿到一个连接
			string sql = $"SELECT * from mall_commodities mc WHERE mc.status = {(int)EnumCommodityStatus.在售} and mc.type = {type} order by mc.sort_index asc;";

			var package = new Package(EnumPackCommand.SC_MallGetAllCommodities_Ret);

			var commodities = conn.Query<mall_commodities>(sql).ToList();

			if (commodities.Count > 0)
			{
				//0表示成功，其余是失败
				package.Write((byte)EnumReqRetStatus.Success);
				package.Write(commodities.Count);
				for (int i = 0; i < commodities.Count; i++)
				{
					package.Write(commodities[i].id);
					package.Write(commodities[i].commodity_name);
					package.Write(commodities[i].sort_index ?? 0);
					package.Write(commodities[i].price ?? 0);
				}
			}
			else
			{
				//非0是失败
				package.Write((byte)EnumReqRetStatus.Fail0);
			}

			session.Send(package);

			Program.ConnectionPool.returnConnection(conn);//连接用完回收
		}


	}
}
